-- bonus
-- create by panyl
-- 道具：  奖励

return {
    apply = function(source, target, classId, value)
        -- 奖励，这里只给玩家奖励
        -- 如果奖励配置了公式，则调用公式计算
        if type(value) == "string" and
            string.startWith(value, "formula_") then
            local prefix = "formula_";
            local formulaName = string.sub(value, string.len(prefix) + 1);

            value = FormulaM.invoke(formulaName, ME.user);
        end

        local function percentAttribBonus(source, attribName, force)
            local value = 0;
            if "hp" == attribName or "mp" == attribName then
                -- 千分比恢复属性
                local maxAttrib = "max_" .. attribName;
                value = math.modf(source:queryAttrib(maxAttrib) * force / 1000);
                -- 可增加上限
                attribName = "limit_" .. attribName;
            else
                -- 千分比增加属性
                -- 清空所有buff、debuff、special
                local baseAttrib = InterfaceM.calcBaseAttrib(source, attribName);

                value = math.modf(baseAttrib * force / 1000);
            end

            -- 最少加1点
            value = math.max(1, value);
            BonusM.doBonus({ 2, attribName, value, }, "apply_property");
        end

        if type(value[1]) == 'number' then
            -- 单个奖励
            -- 特殊处理千分比的属性奖励
            if value[1] == 2 and  type(value[2] == 'string')
                and string.startWith(value[2], "per_") then
                -- 一次性的千分比属性奖励
                local force = value[3];
                local attribName = string.sub(value[2], string.len("per_") + 1);
                percentAttribBonus(source, attribName, force);
            else
                BonusM.doBonus(value, "apply_property");

                -- 龙珠效果需要单独处理
                if value[2] == 1500 then
                    EventMgr.fire(event.GAIN_DRAGON_BALL, { ["num"] = value[3], } );
                end
            end
        else
            -- 多个奖励
            for _, arr in pairs(value) do
                if arr[1] == 2 and  type(arr[2] == 'string')
                    and string.startWith(arr[2], "per_") then
                    -- 一次性的千分比属性奖励
                    local force = arr[3];
                    local attribName = string.sub(arr[2], string.len("per_") + 1);
                    percentAttribBonus(source, attribName, force);
                else
                    BonusM.doBonus(arr, "apply_property");

                    -- 龙珠效果需要单独处理
                    if arr[2] == 1500 then
                        EventMgr.fire(event.GAIN_DRAGON_BALL, { ["num"] = value[3], } );
                    end
                end
            end
        end
    end,
};
